express  = require "express" # Framework itself
coffee   = require "coffee-script"
util     = require "util"
routes   = require "./routes/"
_        = require "./lib/underscore.js"
fs       = require "fs" # File System
puts     = console.log  # a shortcut (for convenience)

# Create server. Attach it to port 7321. Write to console
app = module.exports = express.createServer()
app.listen 7321
console.log "Express server listening on port %d in %s mode", app.address().port, app.settings.env

# <Bob loblaw's law blog>
app.configure ->
  app.set "views", __dirname + "/views"
  app.set "view engine", "jade"
  app.use express.bodyParser()
  app.use express.methodOverride()
  app.use app.router
  app.use express.static(__dirname + "/public")
  app.helpers
    cowbell: (x) -> "Moo #{x} moo!"

app.configure "development", ->
  app.use express.errorHandler
    dumpExceptions: on
    showStack: on

app.configure "production", ->
  app.use express.errorHandler()
# </Bob loblaw's law blog>

# routes is an array consisting of functions.
# each method has a name such as "timeline"
# (which corresponds to "foobar.com/timeline")
#
# app.get(addr, method)
#   addr: e.g. /"timeline"
#   method: routes[r] e.g.:
#     (req, res) -> res.send "hello"
# this automates the mapping.
puts "Available methods:"
for r of routes
  methodName = "/"+r
  puts methodName
  app.get methodName, routes[r]

app.error (err, req, res, next) ->
  res.send err.message, 500

# Dynamically fetch, compile and send javascript
# files to the client side. The files are originally
# in .coffee, so they need to be compiled before
# that can be used. *TODO:* Compile/Everything
# javascriptCache={}
# javascriptCache[filenameNetto]
app.get "/scripts/:scriptname", (req,res) ->
  res.header("Content-Type", "text/javascript")
  filenameNetto = req.params.scriptname.split(".")[0]
  filename = "./public/scripts/"+filenameNetto+".coffee"
  console.log "Trying to compile and send "+filename
  fs.readFile filename, 'utf8', (err,data) ->
    throw err if err
    console.log inspect(data)
    res.send coffee.compile(data)